#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

//父进程向子进程发送消息
int main()
{
    //创建管道
    int fds[2] = {0};
    //fds是写端
    int n = pipe(fds);
    if(n = 0)
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }

    //创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        cerr<<"fork error"<<endl;
        return 2;
    }
    //子进程
    if(id == 0)
    {
        //子进程负责写消息
        close(fds[0]);//关闭读端
        while(true)
        {
            string message = "hello world";
            write(fds[1],message.c_str(),sizeof(message));
            sleep(1);
        }
        exit(0);
    }
    //父进程负责读消息
    if(id > 0)
    {
        char buffer[1024];
        //关闭写端
        close(fds[1]);
        while(true)
        {
            ssize_t n = read(fds[0],buffer,sizeof(buffer));
            if(n > 0)
            {
                cout<<buffer<<endl;
            }
        }
        pid_t rid = waitpid(id,nullptr,0);
    }
    return 0;
}